import React from 'react';

import { getIsAuth } from '@/entities/auth/model/selectors';
import { productApi } from '@/entities/course';
import { innerUrls } from '@/shared/constants';
import { ModalContext } from '@/shared/context/ModalContext';
import { Modals } from '@/shared/interfaces';
import { storage } from '@/shared/lib';
import { useAppSelector } from '@/shared/store';
import { RotationLoader } from '@/shared/ui';
import { useRouter } from 'next/router';

import cs from './SuccessRoute.module.scss';

export const SuccessRoute = ({ OrderId }: { OrderId: string }) => {
  const router = useRouter();
  const isAuth = useAppSelector(getIsAuth);
  const { openModal, setData } = React.useContext(ModalContext);
  const isActuallyAuthenticiated = typeof window !== 'undefined' && storage.getAccessToken() && isAuth;
  const { data, isLoading, error } = productApi.useGetSingleOrderQuery(OrderId, {
    skip: !OrderId,
  });

  const openSuccessModal = () => {
    setData(() => ({
      ...data,
      email: data?.email,
      courseName: data?.items[0]?.title,
      isAuth: isActuallyAuthenticiated,
      isFromSuccess: true,
    }));
    openModal(Modals.SuccessModal);
  };

  React.useEffect(() => {
    if (!isLoading) {
      // @ts-ignore
      if (error.status === 403) {
        router.push(process.env.NEXT_PUBLIC_PURCHASES_DEEPLINK as string);
        window.close();
      } else if (data && data.requestSource === 'site') {
        const destinationUrl = isActuallyAuthenticiated ? innerUrls.profile('purchases') : innerUrls.catalog;
        router.push(destinationUrl).then(() => {
          openSuccessModal();
        });
      }
    }
    if (!isLoading && !isActuallyAuthenticiated) {
      router.push(innerUrls.main);
    }
  }, [OrderId, data, isLoading, isActuallyAuthenticiated]);

  return (
    <div className={cs.container}>
      <RotationLoader />
    </div>
  );
};
